package leetcode.L500;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EX39 {
    int tar = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        tar = target;
        int num = 0;
        int begin = 0;

        dfs(res,path,candidates,num,begin);
        return res;
    }

    private void dfs(List<List<Integer>> res, List<Integer> path,int[] candidates,int num,int begin) {
        if(num==tar){
            res.add(new ArrayList<>(path));
            return;
        }
        else if(num>tar){
            return;
        }
        for (int i = begin; i <candidates.length ; i++) {
            path.add(candidates[i]);
            num+=candidates[i];
            dfs(res,path,candidates,num,i);
            num-=candidates[i];
            path.remove(path.size()-1);
        }

    }
}
